//
//  HttpTool.m
//  easymarketing
//
//  Created by HailongHan on 14/12/22.
//  Copyright (c) 2014年 cubead. All rights reserved.
//

#import "HttpTool.h"
#import <AFNetworking/AFNetworking.h>
#import "AppDelegate.h"

@implementation HttpTool

/**
 *  获取单例http请求管理器
 *
 */
+ (AFHTTPSessionManager *)manager{
    static AFHTTPSessionManager *session_manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        session_manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:HTTP_HOST]];
    });
    return session_manager;
}


+(void)get:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    //获取网络请求管理器
    AFHTTPSessionManager *sessionManager = [self manager];
    sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    [sessionManager GET:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        if (success) {
            if ([self handleException:responseObject]) {
                CMLog(@"服务器返回的结果值：%@",responseObject);
                success(responseObject);
            }
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (error.code == 401) {
            //token过期
//            [[AccountManager manager] logoutAndClearUserInfo];
//            [((AppDelegate *)[UIApplication sharedApplication].delegate) showLoginViewController];
            return;
        }
        if (failure) {
            failure(error);
        }
    }];
}

+(void)post:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    //网络请求管理器
    AFHTTPSessionManager *manager = [self manager];
    //Json
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    
    //Post请求
    [manager POST:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        if (success) {
            if ([self handleException:responseObject]) {        
                CMLog(@"服务器返回的结果值：%@",responseObject);
                success(responseObject);
            }
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (error.code == 401) {
            //token过期
//            [[AccountManager manager] logoutAndClearUserInfo];
//            [((AppDelegate *)[UIApplication sharedApplication].delegate) showLoginViewController];
            return;
        }
        if (failure) {
            failure(error);
        }
    }];
}

+(void)put:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    //网络请求管理器
    AFHTTPSessionManager *manager = [self manager];
    //Json
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    
    //put请求
    [manager PUT:url parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        if (success) {
            if ([self handleException:responseObject]) {
                CMLog(@"服务器返回的结果值：%@",responseObject);
                success(responseObject);
            }
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
//        NSString *errInfo = [error.userInfo objectForKey:@"NSLocalizedDescription"];
//        if ([errInfo isContainsString:@"401"]) {
//            //token过期
//            [[AccountManager manager] logoutAndClearUserInfo];
//            [((AppDelegate *)[UIApplication sharedApplication].delegate) showLoginViewController];
//            return;
//        }
        if (failure) {
            failure(error);
        }
    }];
}

#pragma mark - 上传图片
+ (void)postUploadImage:(NSString*)urlStr andMimeType:(NSArray*)mimeType andData:(NSArray *)data success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    {
        // 本地上传给服务器时,没有确定的URL,不好用MD5的方式处理
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
        
        [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            if (data.count > 0) {
                for (int i = 0; i < data.count; i++) {
                    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                    // 设置日期格式
                    formatter.dateFormat = @"yyyyMMddHH:mm:ss";
                    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
                    NSString *fileName = [NSString stringWithFormat:@"%@%d", dateTime, i];
                    [formData appendPartWithFileData:[data objectAtIndex:i] name:@"image" fileName:fileName mimeType:[mimeType objectAtIndex:i]];
                }
            }
            
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (success) {
                if ([self handleException:responseObject]) {
                    success(responseObject);
                }
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failure) {
                failure(error);
            }
        }];
    }
}


#pragma mark - 随机文件名上传
//+ (void)postUploadImage:(NSString*)urlStr andMimeType:(NSString*)mimeType andData:(NSData *)data success:(void (^)(id))success failure:(void (^)(NSError *))failure{
//    {
//        // 本地上传给服务器时,没有确定的URL,不好用MD5的方式处理
//        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//        manager.responseSerializer = [AFJSONResponseSerializer serializer];
//        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
//        
//        [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//            // 要上传保存在服务器中的名称
//            // 使用时间来作为文件名 2014-04-30 14:20:57.png
//            // 让不同的用户信息,保存在不同目录中
//            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//            // 设置日期格式
//            formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
//            NSString *fileName = [formatter stringFromDate:[NSDate date]];
//            //[formData appendPartWithFormData:data name:fileName];
//            [formData appendPartWithFileData:data name:@"image" fileName:fileName mimeType:mimeType];
//            
//        } progress:^(NSProgress * _Nonnull uploadProgress) {
//            
//        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            if (success) {
//                if ([self handleException:responseObject]) {
//                    CMLog(@"服务器返回的结果值：%@",responseObject);
//                    success(responseObject);
//                }
//            }
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            if (failure) {
//                failure(error);
//            }
//        }];
//    }
//}

+(void)delete:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    //网络请求管理器
    AFHTTPSessionManager *manager = [self manager];
    //Json
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    
    //put请求
    [manager DELETE:url parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        if (success) {
            if ([self handleException:responseObject]) {
                CMLog(@"服务器返回的结果值：%@",responseObject);
                success(responseObject);
            }
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (error.code == 401) {
            //token过期
//            [[AccountManager manager] logoutAndClearUserInfo];
//            [((AppDelegate *)[UIApplication sharedApplication].delegate) showLoginViewController];
            return;
        }
        if (failure) {
            failure(error);
        }
    }];
}

+ (void)download:(NSString *)url progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler {
    /* 创建网络下载对象 */
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    /* 下载地址 */
//    NSURL *url = [NSURL URLWithString:@"http://172.16.10.180:8080/download/Drpg.db"];
    NSURL *URL = [NSURL URLWithString:url];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    /* 下载路径 */
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *filePath = [path stringByAppendingPathComponent:url.lastPathComponent];
    
    /* 开始请求下载 */
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress)  {
        downloadProgressBlock(downloadProgress);
        NSLog(@"下载进度：%.0f％", downloadProgress.fractionCompleted * 100);
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        /* 设定下载到的位置 */
        return [NSURL fileURLWithPath:filePath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        completionHandler(response, filePath, error);
        NSLog(@"下载完成");
        
    }];
    [downloadTask resume];
}



/**
 *
 *
 */
/**
 *  处理一些异常（主要是错误码）
 *
 *
 *  @return 是否继续
 */
+ (BOOL)handleException:(id)responseObject{
    //判断是不是字典
    BOOL isGo = YES;
    
    if ([responseObject isKindOfClass:[NSDictionary class]]) {
        
        if([[responseObject allKeys] containsObject:@"errorCode"] ){
            if ([[responseObject allObjects] containsObject:[NSNumber numberWithFloat:400]]) {
               
            }
        }
    }
    
    return isGo;
}

@end
